<?php

namespace app\admin\controller;

use app\admin\model\SystemUploadfile;
use app\admin\model\Users;
use app\common\controller\AdminController;
use EasyAdmin\annotation\ControllerAnnotation;
use EasyAdmin\annotation\NodeAnotation;
use EasyAdmin\tool\CommonTool;
use jianyan\excel\Excel;
use think\App;
use think\facade\Db;

/**
 * @ControllerAnnotation(title="支出管理")
 */
class Reimbuse extends AdminController
{

    public function __construct(App $app)
    {
        parent::__construct($app);

        $this->model = new \app\admin\model\Reimbuse();
        
        $this->assign('getStatusList', $this->model->getStatusList());

    }

    /**
     * @NodeAnotation(title="待审核")
     */
    public function index()
    {
        if ($this->request->isAjax()) {
            if (input('selectFieds')) {
                return $this->selectList();
            }
            list($page, $limit, $where) = $this->buildTableParames();
            // 强行不联表查询，进行where拦截
            foreach ($where as $k => $v){
                if ($v[0] == 'true_name'){
                    $where[$k] = whereHook($v, 'uid', '\app\admin\model\Users','uid');
                }
            }
            $where[] = ['status', '=', 0];
            $count = $this->model
                ->where($where)
                ->count();
            $list = $this->model
                ->where($where)
                ->page($page, $limit)
                ->order($this->sort)
                ->select();
            foreach ($list as $k => $v){
                $list[$k]['true_name'] = \app\admin\model\Users::where('uid', $v['uid'])->value('true_name');
            }
            $data = [
                'code'  => 0,
                'msg'   => '',
                'count' => $count,
                'data'  => $list,
            ];
            return json($data);
        }
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="已审核")
     */
    public function index2()
    {
        if ($this->request->isAjax()) {
            if (input('selectFieds')) {
                return $this->selectList();
            }
            list($page, $limit, $where) = $this->buildTableParames();
            // 强行不联表查询，进行where拦截
            foreach ($where as $k => $v){
                if ($v[0] == 'true_name'){
                    $where[$k] = whereHook($v, 'uid', '\app\admin\model\Users','uid');
                }
            }
            $where[] = ['status', 'in', [1,2]];
            $count = $this->model
                ->where($where)
                ->count();
            $list = $this->model
                ->where($where)
                ->page($page, $limit)
                ->order($this->sort)
                ->select();
            foreach ($list as $k => $v){
                $list[$k]['true_name'] = \app\admin\model\Users::where('uid', $v['uid'])->value('true_name');
            }
            $data = [
                'code'  => 0,
                'msg'   => '',
                'count' => $count,
                'data'  => $list,
            ];
            return json($data);
        }
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="支出详情")
     */
    public function detail()
    {
        $row = $this->model->find($this->request->param($this->model->getPk()));
        empty($row) && $this->error('记录不存在');
        $row['true_name'] = Users::where('uid', $row['uid'])->value('true_name') ?? '无';
        $row['status'] = $this->model->getstatusList()[$row['status']] ?? '无';
        if ($row['img_ids']){
            $row['img_ids'] = explode(',', $row['img_ids']);
            $row['img_ids'] = SystemUploadfile::whereIn('id', $row['img_ids'])->column('url');
        }else{
            $row['img_ids'] = [];
        }
        $this->assign('row', $row);
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="通过")
     */
    public function through()
    {
        $row = $this->model->find($this->request->param($this->model->getPk()));
        empty($row) && $this->error('记录不存在');
        try {
            $row->status = 1;
            $save = $row->save();
        } catch (\Exception $e) {
            $this->error('审核失败：'.$e->getMessage());
        }
        $save ? $this->success('审核成功') : $this->error('审核失败');
    }

    /**
     * @NodeAnotation(title="驳回")
     */
    public function reject()
    {
        $id = $this->request->param($this->model->getPk());
        $res = $this->model->find($id);
        empty($res) && $this->error('记录不存在');
        if ($this->request->isAjax()){
            try {
                $res->status = 2;
                $res->description = $this->request->param('description','',false);
                $save = $res->save();
            } catch (\Exception $e) {
                $this->error('驳回失败：'.$e->getMessage());
            }
            $save ? $this->success('驳回成功') : $this->error('驳回失败');
        }
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="导出")
     */
    public function export()
    {
        list($page, $limit, $where) = $this->buildTableParames();
        $tableName = $this->model->getName();
        $tableName = CommonTool::humpToLine(lcfirst($tableName));
        $prefix = config('database.connections.mysql.prefix');
        $dbList = Db::query("show full columns from {$prefix}{$tableName}");
        $header = [];
        foreach ($dbList as $vo) {
            $comment = !empty($vo['Comment']) ? $vo['Comment'] : $vo['Field'];
            if (!in_array($vo['Field'], $this->noExportFileds)) {
                $header[] = [$comment, $vo['Field']];
            }
        }
        $list = $this->model
            ->where($where)
            ->limit(100000)
            ->order($this->sort)
            ->select()
            ->toArray();
        $fileName = time();
        return Excel::exportData($list, $header, $fileName, 'xlsx');
    }
}